package com.itheima.appserver.interceptor;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baidu.aip.contentcensor.AipContentCensor;
import com.baidu.aip.contentcensor.EImgType;
import com.itheima.dubbo.interfaces.PublishApi;
import org.bson.types.ObjectId;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class BaiduAuditing {
    @Reference
    PublishApi publishApi;

    public static final String APP_ID = "25379996";
    public static final String API_KEY = "a2378P8v5ZIWYXOzyVBUGwbR";
    public static final String SECRET_KEY = "gz6Rsc021N9RBI41GwgPjjbLaPaYHbS1";


    /**
     * 必须把内容和图片路径绑定在一起判断
     * @param test  内容
     * @param medias    图片路径
     * @param id    朋友圈id
     */
    @Async
    public  void auditing(String test,List<String> medias, ObjectId id) {

        AipContentCensor client = new AipContentCensor(APP_ID, API_KEY, SECRET_KEY);

        Boolean flag = true;

        JSONObject  response = client.textCensorUserDefined(test);
        JSONArray data = (JSONArray) response.get("data");
        if (ObjectUtil.isNotNull(data)) {
            //进入到这说明有不合规内容
            flag = false;
        }

        for (String media : medias) {
            response = client.imageCensorUserDefined(media, EImgType.FILE, null);
            data = (JSONArray) response.get("data");
            if (ObjectUtil.isNotNull(data)) {
                //进入到这说明有不合规图片
                flag = false;
            }
        }

        if (flag) {
            publishApi.setAuditing(id,0L, 2);

        } else {
            publishApi.setAuditing(id,0L,4);
        }

    }
}
